// 有时需要将所有错误都转成一种类型的错误，来简化异常处理

/// - 可以用相同的类型表示不同的错误
/// - 向用户传递友好的消息
/// - 容易与其他类型比对
///  * 好： Err(EmptyVec)
///  * 坏： Err("Please use a vector with at lease one element".to_owned())
/// - 能够包含错误信息
///  * 好： Err(BadChar(c,position))
///  * 坏： Err(" + cannot be used here".to_owned())
/// - 与其他错误能够组合


use std::fmt;

/// 使用了别名
type Result<T> = std::result::Result<T, DoubleError>;

// Define our error types. These may be customized for our error handling cases.
// Now we will be able to write our own errors, defer to an underlying error
// implementation, or do something in between.
// 
#[derive(Debug, Clone)]
struct DoubleError;

// Generation of an error is completely separate from how it is displayed.
// There's no need to be concerned about cluttering complex logic with the display style.
//
// Note that we don't store any extra info about the errors. This means we can't state
// which string failed to parse without modifying our types to carry that information.
/// 注意：由于DoubleError没有额外的错误信息，所以我们只能把错误信息写固定，不然可以显示错误信息。
impl fmt::Display for DoubleError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid first item to double")
    }
}

fn double_first(vec: Vec<&str>) -> Result<i32> {
    vec.first()
        // Change the error to our new type.
        // 记得这个是转换函数，将Option转成Result，所以可以直接返回DoubleError
        // ok_or是作用于Option，Some时返回值，None时返回DoubleError
        .ok_or(DoubleError)
        // and_then是作用于result，OK时返回值，Err时返回DoubleError
        .and_then(|s| {
            s.parse::<i32>()
                // Update to the new error type here also.
                // 这里也是转换函数，所以可以直接返回DoubleError
                .map_err(|_| DoubleError)
                // Map用来操作的是result的结果，返回的也是Ok(2*i)
                .map(|i| 2 * i)
        })
}

fn print(result: Result<i32>) {
    match result {
        Ok(n) => println!("The first doubled is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

fn main() {
    let numbers = vec!["42", "93", "18"];
    let empty = vec![];
    let strings = vec!["tofu", "93", "18"];

    print(double_first(numbers));
    print(double_first(empty));
    print(double_first(strings));
}